package no.nordicsemi.android.nrfmesh;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import no.nordicsemi.android.nrfmesh.database.entity.SentProfile;

public class SentProfileAdapter extends RecyclerView.Adapter<SentProfileAdapter.GroupViewHolder> {

    private final Context context;
    private List<GroupedProfile> groupedProfiles = new ArrayList<>();
    private OnItemClickListener listener; // 点击监听器
    private OnItemDeleteListener deleteListener; // 删除监听器

    // 构造方法
    public SentProfileAdapter(Context context) {
        this.context = context;
    }

    // 设置删除监听器
    public void setOnDeleteClickListener(OnItemDeleteListener listener) {
        this.deleteListener = listener;
    }

    // 设置点击监听器
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    // 更新数据
    public void updateProfiles(List<SentProfile> profiles) {
        // 按组ID分组
        Map<String, List<SentProfile>> groupMap = new HashMap<>();
        for (SentProfile profile : profiles) {
            if (profile.groupId != null && !profile.groupId.isEmpty()) {
                if (!groupMap.containsKey(profile.groupId)) {
                    groupMap.put(profile.groupId, new ArrayList<>());
                }
                groupMap.get(profile.groupId).add(profile);
            }
        }

        // 转换为GroupedProfile列表
        groupedProfiles.clear();
        for (Map.Entry<String, List<SentProfile>> entry : groupMap.entrySet()) {
            // 按segmentIndex排序
            entry.getValue().sort((a, b) -> Integer.compare(a.segmentIndex, b.segmentIndex));
            groupedProfiles.add(new GroupedProfile(entry.getKey(), entry.getValue()));
        }

        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public GroupViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(context).inflate(R.layout.item_sent_profile, parent, false);
        return new GroupViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull GroupViewHolder holder, int position) {
        GroupedProfile groupedProfile = groupedProfiles.get(position);
        
        // 设置组标题（显示配置名称）
        String configName = groupedProfile.profiles.get(0).configName;
        if (configName != null && !configName.isEmpty()) {
            holder.tvGroupTitle.setText(configName + " (" + groupedProfile.profiles.size() + "段)");
        } else {
            holder.tvGroupTitle.setText("组配置 (" + groupedProfile.profiles.size() + "段)");
        }
        
        // 设置段参数适配器
        SegmentParamAdapter segmentAdapter = new SegmentParamAdapter(context, groupedProfile.profiles);
        holder.rvSegmentParams.setLayoutManager(new LinearLayoutManager(context));
        holder.rvSegmentParams.setAdapter(segmentAdapter);
        
        // 设置点击事件
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemClick(groupedProfile.profiles);
            }
        });
        
        // 设置删除按钮点击事件
        holder.btnDelete.setOnClickListener(v -> {
            if (deleteListener != null) {
                deleteListener.onItemDelete(groupedProfile.profiles);
            }
        });
    }

    @Override
    public int getItemCount() {
        return groupedProfiles.size();
    }

    // 组配置数据类
    public static class GroupedProfile {
        public String groupId;
        public List<SentProfile> profiles;

        public GroupedProfile(String groupId, List<SentProfile> profiles) {
            this.groupId = groupId;
            this.profiles = profiles;
        }
    }

    // 组ViewHolder
    static class GroupViewHolder extends RecyclerView.ViewHolder {
        private final TextView tvGroupTitle;
        private final RecyclerView rvSegmentParams;
        private final View btnDelete;

        public GroupViewHolder(@NonNull View itemView) {
            super(itemView);
            tvGroupTitle = itemView.findViewById(R.id.tvGroupTitle);
            rvSegmentParams = itemView.findViewById(R.id.rvSegmentParams);
            btnDelete = itemView.findViewById(R.id.btnDelete);
        }
    }

    // 段参数适配器
    private static class SegmentParamAdapter extends RecyclerView.Adapter<SegmentParamAdapter.SegmentViewHolder> {
        private final Context context;
        private final List<SentProfile> profiles;

        public SegmentParamAdapter(Context context, List<SentProfile> profiles) {
            this.context = context;
            this.profiles = profiles;
        }

        @NonNull
        @Override
        public SegmentViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(context).inflate(R.layout.item_segment_param, parent, false);
            return new SegmentViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(@NonNull SegmentViewHolder holder, int position) {
            SentProfile profile = profiles.get(position);
            
            holder.tvSegmentIndex.setText("段" + profile.segmentIndex + ":");
            holder.tvSegmentDuration.setText(profile.segmentDuration + "ms");
            holder.tvWaveformType.setText(profile.waveformType);
            holder.tvPulseWidth.setText(profile.pulseWidth + "μs");
            holder.tvFrequency.setText(profile.frequency + "Hz");
        }

        @Override
        public int getItemCount() {
            return profiles.size();
        }

        static class SegmentViewHolder extends RecyclerView.ViewHolder {
            private final TextView tvSegmentIndex;
            private final TextView tvSegmentDuration;
            private final TextView tvWaveformType;
            private final TextView tvPulseWidth;
            private final TextView tvFrequency;

            public SegmentViewHolder(@NonNull View itemView) {
                super(itemView);
                tvSegmentIndex = itemView.findViewById(R.id.tvSegmentIndex);
                tvSegmentDuration = itemView.findViewById(R.id.tvSegmentDuration);
                tvWaveformType = itemView.findViewById(R.id.tvWaveformType);
                tvPulseWidth = itemView.findViewById(R.id.tvPulseWidth);
                tvFrequency = itemView.findViewById(R.id.tvFrequency);
            }
        }
    }

    // 点击事件接口
    public interface OnItemClickListener {
        void onItemClick(List<SentProfile> profiles);
    }

    // 删除监听器接口
    public interface OnItemDeleteListener {
        void onItemDelete(List<SentProfile> profiles);
    }
}

